using System.Diagnostics.CodeAnalysis;
using BootstrapBlazor.Components;
using Identity.Interface;
using Identity.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using Identity.Extensions;
namespace Identity.Account.Setting;
public partial class NavigationManage: ComponentBase 
{



  public static List<SelectedItem> GetTargets() => new()
  {
      new SelectedItem("_self", "本窗口"),
      new SelectedItem("_blank", "新窗口"),
      new SelectedItem("_parent", "父级窗口"),
      new SelectedItem("_top", "顶级窗口"),
  };
    [Inject]
    [NotNull]
    private INavigation? NavigationService { get; set; }

    /// <summary>
    /// 
    /// </summary>
    [Parameter]
    [EditorRequired]
    [NotNull]
    public List<SelectedItem>? ParementMenus { get; set; }
    [NotNull]
    private List<SelectedItem>? Targets { get; set; }

     protected override void OnInitialized()
 {
     base.OnInitialized();

     Targets = GetTargets();

 }
    private Task<IEnumerable<TableTreeNode<Navigation>>> OnTreeExpand(Navigation menu)
  {
      var navs = NavigationService.GetAllMenus();
      return Task.FromResult(navs.Where(m => m.ParentId == menu.Id).OrderBy(m => m.Order).AsEnumerable().Select(i => new TableTreeNode<Navigation>(i)));
  }
  private Task<QueryData<Navigation>> OnQueryAsync(QueryPageOptions options)
  {
      var navs = NavigationService.GetAllMenus();
      var menus = navs.Where(m =>string.IsNullOrEmpty(m.ParentId));

      // 处理模糊查询
      if (options.Searches.Any())
      {
          menus = menus.Where(options.Searches.GetFilterFunc<Navigation>(FilterLogic.Or));
      }

      //  处理 Filter 高级搜索
      if (options.CustomerSearches.Any() || options.Filters.Any())
      {
          menus = menus.Where(options.CustomerSearches.Concat(options.Filters).GetFilterFunc<Navigation>());
      }

      foreach (var item in menus)
      {
          item.HasChildren = navs.Any(i => i.ParentId == item.Id);
      }

      return Task.FromResult(new QueryData<Navigation>()
      {
          IsFiltered = true,
          IsSearch = true,
          IsSorted = true,
          Items = menus
      });
  }

 private Task<IEnumerable<TableTreeNode<Navigation>>> TreeNodeConverter(IEnumerable<Navigation> items)
  {
      var ret = BuildTreeNodes(items,  string.Empty);
      return Task.FromResult(ret);

      IEnumerable<TableTreeNode<Navigation>> BuildTreeNodes(IEnumerable<Navigation> items, string? parentId)
      {
          var navs = NavigationService.GetAllMenus();
          var ret = new List<TableTreeNode<Navigation>>();
          ret.AddRange(items.Where(i => i.ParentId == parentId).Select((nav, index) => new TableTreeNode<Navigation>(nav)
          {
              HasChildren = navs.Any(i => i.ParentId == nav.Id),
              IsExpand = navs.Any(i => i.ParentId == nav.Id),
              Items = BuildTreeNodes(navs.Where(i => i.ParentId == nav.Id), nav.Id)
          }));
          return ret;
      }
  }
}